import login from '@/views/Login.vue'
import { createRouter, createWebHistory } from 'vue-router'
import layout from '@/views/Layout.vue'
import articleCategory from '@/views/article/ArticleCategory.vue'
import articleManage from '@/views/article/ArticleManage.vue'
import userAvatar from '@/views/user/UserAvatar.vue'
import userInfo from '@/views/user/UserInfo.vue'
import userResetPassword from '@/views/user/UserResetPassword.vue'
import { useTokenStore } from '@/store/token.js'
import { ElMessage } from "element-plus"

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/login',
            component: login
        },
        {
            path: '/',
            component: layout,
            redirect: '/article/manage',
            children: [
                {
                    path: '/article/category',
                    component: articleCategory
                },
                {
                    path: '/article/manage',
                    component: articleManage
                },
                {
                    path: '/user/avatar',
                    component: userAvatar
                },
                {
                    path: '/user/info',
                    component: userInfo
                },
                {
                    path: '/user/resetPassword',
                    component: userResetPassword
                }
            ]
        }
    ]
})


// 添加路由卫士
router.beforeEach((to, from, next) => {
    // 获取token(通过pinia获取)
    const tokenStore = useTokenStore()
    const token = tokenStore.token
    // 如果没有token, 并且不是登录页, 则跳转至登录页
    if ((!token && to.path !== '/login')) {
        ElMessage.error('请先登录')
        next('/login')
    } else {
        next()
    }
})


// 导出路由
export default router